const jwt = require('jsonwebtoken')
const { error } = require('../lib/response')

function verifyToken(req, res, next) {
  const token = req.headers.authorization?.replace('Bearer ', '')
  
  if (!token) {
    return res.status(401).json(error('未提供认证令牌', 401))
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    req.user = decoded
    next()
  } catch (err) {
    return res.status(401).json(error('无效的认证令牌', 401))
  }
}

module.exports = {
  verifyToken
}
